use crate::tools::str_tools;
use reqwest::header::{HeaderMap, HeaderValue, COOKIE, REFERER, USER_AGENT};
use serde_json::Value;
use std::collections::HashMap;
use std::error::Error;
pub async fn get_bili_url(iframe: &str, cookie: &str) -> Result<String, Box<dyn Error>> {
    let avid = str_tools::extract_between(iframe, "aid=", "&").ok_or("iframe src解析失败")?;
    let cid = str_tools::extract_between(iframe, "cid=", "&").ok_or("iframe src解析失败")?;
    // 构建请求头
    let mut headers = HeaderMap::new();
    headers.insert(COOKIE, HeaderValue::from_str(cookie)?);
    headers.insert(
        USER_AGENT,
        HeaderValue::from_str("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36 Edg/140.0.0.0")?,
    );
    headers.insert(REFERER, HeaderValue::from_str("https://www.bilibili.com/")?);

    let mut params = HashMap::new();
    params.insert("avid", avid);
    params.insert("cid", cid);
    params.insert("type", "mp4");
    params.insert("platform", "html5");
    params.insert("qn", "16");

    let client = reqwest::Client::builder()
        .default_headers(headers)
        .build()?;

    let response = client
        .get("https://api.bilibili.com/x/player/wbi/playurl")
        .query(&params)
        .send()
        .await?;

    if !response.status().is_success() {
        return Err(format!("请求错误，状态码: {}", response.status()).into());
    }
    let json = response.text().await?;

    let info: Value =
        serde_json::from_str(&json).map_err(|e| format!("解析返回信息失败: {}", e))?;
    let url = info["data"]["durl"]
        .as_array()
        .ok_or(format!("查找url失败,错误信息{}", info.to_string()))?[0]["url"]
        .as_str()
        .ok_or(format!("查找url失败,错误信息{}", info.to_string()))?;
    Ok(String::from(url))
}
